import React, { useState } from 'react';
import {
  Modal,
  Form,
  Input,
  Button,
  InputNumber,
  Select,
  Space,
  Divider,
  Row,
  Col,
  message,
  DatePicker,
  Switch,
  Card,
} from 'antd';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import type { SyncUserprofileRequest, Assets, FamilyMembers, RelationDetail } from '@/types';
import { userAPI } from '@/services/api';
import dayjs from 'dayjs';

const { Option } = Select;
const { TextArea } = Input;

interface NewUserFormProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

const NewUserForm: React.FC<NewUserFormProps> = ({ visible, onCancel, onSuccess }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      // 构建用户档案数据
      const userProfileData: SyncUserprofileRequest = {
        userNum: values.userNum,
        name: values.name,
        gender: values.gender,
        height: values.height,
        weight: values.weight,
        birthDate: values.birthDate ? dayjs(values.birthDate).format('YYYY-MM-DD') : '',
        maritalStatus: values.maritalStatus,
        assets: {
          annualIncome: values.annualIncome || 0,
          car: values.car || '无',
          house: values.house || '无',
        },
        education: values.education,
        occupation: values.occupation,
        isPartyMember: values.isPartyMember || false,
        hometown: values.hometown,
        currentResidence: values.currentResidence,
        familyMembers: {
          familyType: values.familyType || '',
          fatherDetail: {
            age: values.fatherAge,
            desc: values.fatherDesc || '',
          },
          motherDetail: {
            age: values.motherAge,
            desc: values.motherDesc || '',
          },
          otherDetail: values.otherMembers || [],
        },
        createUser: 'admin', // 这里可以从当前登录用户获取
        modifyUser: 'admin',
      };

      console.log('提交用户档案数据:', userProfileData);

      const response = await userAPI.syncUserProfile(userProfileData);

      if (response && response.code === 0) {
        message.success('新增用户档案成功！');
        form.resetFields();
        onSuccess();
      } else {
        message.error(response?.msg || '操作失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败，请检查表单');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title="新增用户档案"
      open={visible}
      onCancel={onCancel}
      width={1000}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={loading} onClick={handleSubmit}>
          提交
        </Button>,
      ]}
      style={{ top: 20 }}
      bodyStyle={{ maxHeight: '70vh', overflowY: 'auto' }}
    >
      <Form
        form={form}
        layout="vertical"
        requiredMark={false}
      >
        <Divider orientation="left">基本信息</Divider>
        
        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              label="用户编号"
              name="userNum"
              rules={[{ required: true, message: '请输入用户编号' }]}
            >
              <InputNumber
                placeholder="请输入用户编号"
                style={{ width: '100%' }}
                min={1}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="姓名"
              name="name"
              rules={[{ required: true, message: '请输入姓名' }]}
            >
              <Input placeholder="请输入姓名" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="性别"
              name="gender"
              rules={[{ required: true, message: '请选择性别' }]}
            >
              <Select placeholder="请选择性别">
                <Option value="男">男</Option>
                <Option value="女">女</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              label="身高 (厘米)"
              name="height"
              rules={[{ required: true, message: '请输入身高' }]}
            >
              <InputNumber
                placeholder="请输入身高"
                min={100}
                max={250}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="体重 (斤)"
              name="weight"
              rules={[{ required: true, message: '请输入体重' }]}
            >
              <InputNumber
                placeholder="请输入体重"
                min={50}
                max={500}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="生日"
              name="birthDate"
              rules={[{ required: true, message: '请选择生日' }]}
            >
              <DatePicker
                placeholder="请选择生日"
                style={{ width: '100%' }}
                format="YYYY-MM-DD"
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              label="婚姻状态"
              name="maritalStatus"
              rules={[{ required: true, message: '请选择婚姻状态' }]}
            >
              <Select placeholder="请选择婚姻状态">
                <Option value="未婚">未婚</Option>
                <Option value="离异">离异</Option>
                <Option value="丧偶">丧偶</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="教育经历"
              name="education"
              rules={[{ required: true, message: '请选择教育经历' }]}
            >
              <Select placeholder="请选择教育经历">
                <Option value="小学">小学</Option>
                <Option value="初中">初中</Option>
                <Option value="中专">中专</Option>
                <Option value="高中">高中</Option>
                <Option value="大专">大专</Option>
                <Option value="本科">本科</Option>
                <Option value="硕士">硕士</Option>
                <Option value="博士">博士</Option>
                <Option value="博士后">博士后</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="职业"
              name="occupation"
              rules={[{ required: true, message: '请选择职业' }]}
            >
              <Select placeholder="请选择职业">
                <Option value="公务员">公务员</Option>
                <Option value="教师">教师</Option>
                <Option value="医生">医生</Option>
                <Option value="护士">护士</Option>
                <Option value="律师">律师</Option>
                <Option value="法官">法官</Option>
                <Option value="警察">警察</Option>
                <Option value="自由职业者">自由职业者</Option>
                <Option value="经商">经商</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              label="籍贯"
              name="hometown"
              rules={[{ required: true, message: '请选择籍贯' }]}
            >
              <Select placeholder="请选择籍贯">
                <Option value="广德">广德</Option>
                <Option value="郎溪">郎溪</Option>
                <Option value="宁国">宁国</Option>
                <Option value="宣城">宣城</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="现居住地/工作地"
              name="currentResidence"
              rules={[{ required: true, message: '请选择现居住地' }]}
            >
              <Select placeholder="请选择现居住地">
                <Option value="上海">上海</Option>
                <Option value="杭州">杭州</Option>
                <Option value="合肥">合肥</Option>
                <Option value="北京">北京</Option>
                <Option value="南京">南京</Option>
                <Option value="芜湖">芜湖</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="是否党员"
              name="isPartyMember"
              valuePropName="checked"
            >
              <Switch checkedChildren="是" unCheckedChildren="否" />
            </Form.Item>
          </Col>
        </Row>

        <Divider orientation="left">个人资产状态</Divider>
        
        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              label="年收入 (万元)"
              name="annualIncome"
              rules={[{ required: true, message: '请输入年收入' }]}
            >
              <InputNumber
                placeholder="请输入年收入"
                min={0}
                step={0.1}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="车子状态"
              name="car"
              rules={[{ required: true, message: '请选择车子状态' }]}
            >
              <Select placeholder="请选择车子状态">
                <Option value="全款">全款</Option>
                <Option value="按揭">按揭</Option>
                <Option value="无">无</Option>
                <Option value="随时买">随时买</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="房子状态"
              name="house"
              rules={[{ required: true, message: '请选择房子状态' }]}
            >
              <Select placeholder="请选择房子状态">
                <Option value="城区全款房">城区全款房</Option>
                <Option value="城区按揭房">城区按揭房</Option>
                <Option value="乡镇房">乡镇房</Option>
                <Option value="随时买">随时买</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Divider orientation="left">家庭成员信息</Divider>
        
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              label="家庭类型备注"
              name="familyType"
            >
              <Input placeholder="如：单亲家庭等特殊情况" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Card title="父亲情况" size="small">
              <Form.Item
                label="年龄"
                name="fatherAge"
              >
                <InputNumber
                  placeholder="请输入父亲年龄"
                  min={0}
                  max={120}
                  style={{ width: '100%' }}
                />
              </Form.Item>
              <Form.Item
                label="情况介绍"
                name="fatherDesc"
              >
                <TextArea
                  placeholder="如：职业、收入、老师/在职/退休/经商等"
                  rows={3}
                />
              </Form.Item>
            </Card>
          </Col>
          <Col span={12}>
            <Card title="母亲情况" size="small">
              <Form.Item
                label="年龄"
                name="motherAge"
              >
                <InputNumber
                  placeholder="请输入母亲年龄"
                  min={0}
                  max={120}
                  style={{ width: '100%' }}
                />
              </Form.Item>
              <Form.Item
                label="情况介绍"
                name="motherDesc"
              >
                <TextArea
                  placeholder="如：职业、收入、老师/在职/退休/经商等"
                  rows={3}
                />
              </Form.Item>
            </Card>
          </Col>
        </Row>

        <Divider orientation="left">其他家庭成员</Divider>
        
        <Form.List name="otherMembers">
          {(fields, { add, remove }) => (
            <>
              {fields.map(({ key, name, ...restField }) => (
                <Card key={key} size="small" style={{ marginBottom: 16 }}>
                  <Row gutter={16} align="middle">
                    <Col span={8}>
                      <Form.Item
                        {...restField}
                        name={[name, 'age']}
                        label="年龄"
                      >
                        <InputNumber
                          placeholder="年龄"
                          min={0}
                          max={120}
                          style={{ width: '100%' }}
                        />
                      </Form.Item>
                    </Col>
                    <Col span={14}>
                      <Form.Item
                        {...restField}
                        name={[name, 'desc']}
                        label="情况介绍"
                      >
                        <Input placeholder="如：兄弟姐妹、职业、收入等" />
                      </Form.Item>
                    </Col>
                    <Col span={2}>
                      <Button
                        type="text"
                        danger
                        icon={<MinusCircleOutlined />}
                        onClick={() => remove(name)}
                      />
                    </Col>
                  </Row>
                </Card>
              ))}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add()}
                  block
                  icon={<PlusOutlined />}
                >
                  添加其他家庭成员
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
      </Form>
    </Modal>
  );
};

export default NewUserForm;